﻿using System;
using System.Web;
using System.Xml;
using System.Xml.Xsl;
using Altairis.Nemesis.Gallery.Configuration;

namespace Altairis.Nemesis.Gallery {

    public class ConfiguredXsltArgumentList : XsltArgumentList {

        public const string NamespaceDynamic = "http://schemas.altairis.cz/Nemesis/Gallery/XsltArguments#Dynamic";
        public const string NamespaceQueryString = "http://schemas.altairis.cz/XML4web/Arguments#QueryString";
        public const string NamespaceFormFields = "http://schemas.altairis.cz/XML4web/Arguments#FormFields";

        public ConfiguredXsltArgumentList(bool forwardParams)
            : base() {

            GallerySection config = GallerySection.GetCurrentOrDefault();

            // Add parameters read from configuration
            foreach (TemplateParameterElement param in config.TemplateParameters) {
                this.AddParam(param.Name, param.Namespace, param.Value);
            }

            if (forwardParams) {
                // Append query string values
                foreach (var key in HttpContext.Current.Request.QueryString.AllKeys) {
                    if (key == null) continue;
                    this.AddParam(key, NamespaceQueryString, HttpContext.Current.Request.QueryString[key]);
                }
                // Append form field values
                foreach (var key in HttpContext.Current.Request.Form.AllKeys) {
                    if (key == null) continue;
                    this.AddParam(key, NamespaceFormFields, HttpContext.Current.Request.Form[key]);
                }
            }

            // Add parameters generated dynamically
            this.AddParam("CurrentTime", NamespaceDynamic, XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.Local));
            this.AddParam("HostName", NamespaceDynamic, System.Web.HttpContext.Current.Request.Url.Host);
        }

    }

}
